package com.lavegue.webaction;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.lavegue.common.BaseAction;
import com.lavegue.common.Constants;
import com.lavegue.model.Area;
import com.lavegue.model.Company;
import com.lavegue.model.UserInfo;
import com.lavegue.service.AreaService;
import com.lavegue.service.CompanyService;
import com.lavegue.service.UserInfoService;
import com.opensymphony.xwork2.ActionContext;
import com.sun.net.httpserver.HttpContext;

/**
 * author: luoweibin 
 * date:2011-12-19 
 * description: 公共的文件上传
 */
public class FileUploadAction extends BaseAction {

	// 图片文件
	private File pic;
	// 图片文件类型
	private String picContentType;
	// 文件名
	private String picFileName;
	// 允许的文件类型，在action里面配置
	private String allowTypes;
	private long maximumSize;
	private UserInfoService userService;
	private String jspFileName;
	private UserInfo user;
	private CompanyService companyService;
	private AreaService areaService;
	// 省列表
	private List<Area> provinces;
	// 城市列表
	private List<Area> cityList;
	// 区域列表
	private List<Area> areaList;
	// 省份ID
	private Integer sf_id;
	// 城市ID
	private Integer cs_id;
	// 区域ID
	private Integer qy_id;
	
	public String getJspFileName() {
		return jspFileName;
	}

	public void setJspFileName(String jspFileName) {
		this.jspFileName = jspFileName;
	}

	/**
	 * 前台修改用户 上传图片Logo
	 * 
	 * @return
	 */
	public String uploadEnterpriseLogo() {
//		if (pic == null) {
//			this.addActionError("请选择您要上传的图片.");
//			return INPUT;
//		}
		
		String filterResult = this.filterType(this.getAllowTypes().split(","));
		if (filterResult != null) {
			this.addActionError("上传的文件格式不正确,请重新选择");
			initMethodArea();
			//return "backModUserPage";
			return "modLogoSucc";
		}
		if ((pic.length()/1024) > maximumSize) {
			this.addActionError("图片格式过大无法上传.");
			if(null == getSessionAtrribute("errFileSize")){
				setSessionAtrribute("errFileSize", "图片格式过大无法上传.");
			}
			initMethodArea();		
			//return INPUT;
		//	return "backModUserPage";
			return "modLogoSucc";
		}else{
			removeSession("errFileSize");
		}
		
		//图片上传的路径,包括文件名的全路径
		String fileNmae = Constants.IMG_UPLOAD_PATH +"_" +  System.currentTimeMillis() + "." + FilenameUtils.getExtension(picFileName);
		String savePath  = this.getProjectPath() + fileNmae;
		UserInfo userinfo = this.getSessionUser();
//		System.out.println("文件路径=====>>>>>>>>>>>>>>"+savePath);
		File destFile = new File(savePath);
		try {
			destFile.createNewFile();
			FileUtils.copyFile(pic, destFile);

			// 如果原来有图片先删除掉
			if(!StringUtils.isBlank(userinfo.getPersonalIco())) {
				File old = new File(this.getProjectPath() + userinfo.getPersonalIco());
				if (old.exists()) {
					old.delete();
				}
			}
			
			//更新用户信息
			//userService.modifyUserInfo(user);
			ActionContext.getContext().put("logoPath", fileNmae);
			//在修改用户信息页面获取(userInfoModify.jsp)
			if(null == getSessionAtrribute("imgIcoPath")){
				setSessionAtrribute("imgIcoPath", fileNmae);
			}else{
				removeSession("imgIcoPath");
				setSessionAtrribute("imgIcoPath", fileNmae);
			}
			
			// 先清除session中user
			//removeSession(Constants.SESSION_USER);
			//user.setPersonalIco(fileNmae);  //图片路径名称
			// 在把新user放入session中
			//setSessionAtrribute(Constants.SESSION_USER, user);
			
			// 先清除session中图片路径
			//removeSession("imgIcoPath");
			
			//setSessionAtrribute("imgIcoPath", fileNmae);
			initMethodArea();
				
		} catch (IOException e) {
//			e.printStackTrace();
			LOG.error("上传文件复制异常:", e);
		}
		
	//	return SUCCESS;
		return "modLogoSucc";
	}

	/**20120105
	 * 后台添加和修改用户时上传图片(userInfoAdd.jsp)
	 * 上传图片Logo
	 * @return
	 */
	public String uploadUserLogo() {
//		if (pic == null) {
//			this.addActionError("请选择您要上传的图片");
//			return INPUT;
//		}
		
		if(null != jspFileName && jspFileName.equals("bsUserInfoModify.jsp")){  //修改用户页面
			if ((pic.length()/1024) > maximumSize) {
				//this.addActionError("上传的文件过大,请重新选择");
				if(null == getSessionAtrribute("htErrFileSize")){
					setSessionAtrribute("htErrFileSize", "图片格式过大无法上传.");
				}
				return "modUserSucc";    //处理-跳转到 [backStageManage/bsUserInfoModify.jsp]后台修改用户页面
			}else{
				removeSession("htErrFileSize");
			}
		}
		else{  //添加用户页面
			if ((pic.length()/1024) > maximumSize) {
				if(null == getSessionAtrribute("htErrFileSize")){
					setSessionAtrribute("htErrFileSize", "图片格式过大无法上传.");
				}
				
				//获取所有的公司名称
				List<Company> comList = companyService.findByCompany();
				String shengfen = "";
				String chengshi = "";
				String  quyu = "";
				// 获取省列表,在前台显示省份
				provinces = areaService.findAreaByParendIdAndlvType(Area.NO_PARENT,
						Area.AreaType.PROVINCE);
				if(null != user){
					if(null != user.getProvince() && !user.getProvince().equals("")){
						String provinceid =	user.getProvince(); //省份ID
						//通过省份ID查询获取名称
						 Area areaProvince = areaService.findById(Integer.valueOf(provinceid));
						 shengfen = areaProvince.getName(); //获取省份
					 }
					 
					 if(null != user.getCity() && !user.getCity().equals("")){
						 String cityid =user.getCity();  //城市ID
						 Area areaCity = areaService.findById(Integer.valueOf(cityid));
						 chengshi = areaCity.getName(); //获取城市
					 }
					 if(null != user.getZone() && !user.getZone().equals("")){
						 String zoneid= user.getZone();   //区县ID
						 Area areaZone = areaService.findById(Integer.valueOf(zoneid));
						 quyu = areaZone.getName();  //获取区县
					 }

					 if(shengfen.equals("")){
						 Area area = new Area();
							area.setId(0);
							area.setName("请选择...");
						 cityList = new ArrayList<Area>();
						 cityList.add(area);
						 areaList = new ArrayList<Area>();
						 areaList.add(area);
					 }else {
						// 查询省份的一条记录
						List<Area> sfList = areaService.findAreaByNameTypeid(shengfen,Area.AreaType.PROVINCE); 
						for (int i = 0; i < sfList.size(); i++) {
							Area sf_area = sfList.get(i);
							sf_id = sf_area.getId(); // 得到省份ID<*>
							// 通过省份ID查询所有城市，页面获取值<*>
							cityList = areaService.findAreaByParendIdAndlvType(sf_id,Area.AreaType.CITY);
							   // 查询城市的一条记录
								if(!chengshi.equals("")){
									List<Area> csList = areaService.findAreaByName(chengshi, sf_id);
									for (int j = 0; j < csList.size(); j++){
										Area cs_area = csList.get(j);
										cs_id = cs_area.getId(); // 得到城市ID<*>
										
										Area area = new Area();
										area.setId(0);
										area.setName("请选择...");
										
										// 通过城市ID查询所有的区域，页面获取值<*>
										areaList = areaService.findAreaByParendIdAndlvType(cs_id, Area.AreaType.AREA);
										areaList.add(0, area);
										// 查询区域的一条记录
										if(!quyu.equals("")){
											List<Area> qyList = areaService.findAreaByName(quyu, cs_id); 
											for (int k = 0; k < qyList.size(); k++) {
												Area qy_area = qyList.get(j);
												qy_id = qy_area.getId(); // 得到区域ID<*>
											}
										}
									}
								}else{
									Area area = new Area();
									area.setId(0);
									area.setName("请选择...");
									cityList.add(0, area);
									areaList = new ArrayList<Area>();
									areaList.add(area);
								}
								 
		
						}
					}
				}
				setRequestAtrribute("companyList", comList);
				
				return "addUserSucc"; //处理-跳转到 [backStageManage/userInfoAdd.jsp]后台添加用户页面
			}else{
				removeSession("htErrFileSize");
			}
		}
//		String filterResult = this.filterType(this.getAllowTypes().split(","));
//		if (filterResult != null) {
//			this.addActionError("您上传的文件类型不正确,请重新选择");
//			return INPUT;
//		}
	
		//图片上传的路径,包括文件名的全路径
		String fileNmae = Constants.IMG_UPLOAD_PATH + "_" +  System.currentTimeMillis() + "." + FilenameUtils.getExtension(picFileName);
		String savePath  = this.getProjectPath() + fileNmae;
//		System.out.println("文件路径=====>>>>>>>>>>>>>>"+savePath);
		File destFile = new File(savePath);
		try {
			destFile.createNewFile();
			FileUtils.copyFile(pic, destFile);

			// 如果原来有图片先删除掉
			if(!StringUtils.isBlank(pic.getPath())) {
				File old = new File(this.getProjectPath() + pic.getPath());
				if (old.exists()) {
					old.delete();
				}
			}
		
			//更新用户信息
		//	userService.modifyUserInfo(user);
			ActionContext.getContext().put("logoPath", fileNmae);
			
			// 先清除session中图片路径
			removeSession("htImgIcoPath");
			//user.setPersonalIco(fileNmae);  //图片路径名称
			// 在把新user放入session中
			//setSessionAtrribute(Constants.SESSION_USER, user);
			
			setSessionAtrribute("htImgIcoPath", fileNmae);
		} catch (IOException e) {
//			e.printStackTrace();
			LOG.error("上传文件复制异常:", e);
		}
		
		if(null != jspFileName && jspFileName.equals("bsUserInfoModify.jsp")){
			return "modUserSucc";    //处理-跳转到 [backStageManage/bsUserInfoModify.jsp]后台修改用户页面
		}
		else{
			//获取所有的公司名称
			List<Company> comList = companyService.findByCompany();
			String shengfen = "";
			String chengshi = "";
			String  quyu = "";
			// 获取省列表,在前台显示省份
			provinces = areaService.findAreaByParendIdAndlvType(Area.NO_PARENT,
					Area.AreaType.PROVINCE);
			if(null != user){
				if(null != user.getProvince() && !user.getProvince().equals("")){
					String provinceid =	user.getProvince(); //省份ID
					//通过省份ID查询获取名称
					 Area areaProvince = areaService.findById(Integer.valueOf(provinceid));
					 shengfen = areaProvince.getName(); //获取省份
				 }
				 
				 if(null != user.getCity() && !user.getCity().equals("")){
					 String cityid =user.getCity();  //城市ID
					 Area areaCity = areaService.findById(Integer.valueOf(cityid));
					 chengshi = areaCity.getName(); //获取城市
				 }
				 if(null != user.getZone() && !user.getZone().equals("")){
					 String zoneid= user.getZone();   //区县ID
					 Area areaZone = areaService.findById(Integer.valueOf(zoneid));
					 quyu = areaZone.getName();  //获取区县
				 }

				 if(shengfen.equals("")){
					 Area area = new Area();
						area.setId(0);
						area.setName("请选择...");
					 cityList = new ArrayList<Area>();
					 cityList.add(area);
					 areaList = new ArrayList<Area>();
					 areaList.add(area);
				 }else {
					// 查询省份的一条记录
					List<Area> sfList = areaService.findAreaByNameTypeid(shengfen,Area.AreaType.PROVINCE); 
					for (int i = 0; i < sfList.size(); i++) {
						Area sf_area = sfList.get(i);
						sf_id = sf_area.getId(); // 得到省份ID<*>
						// 通过省份ID查询所有城市，页面获取值<*>
						cityList = areaService.findAreaByParendIdAndlvType(sf_id,Area.AreaType.CITY);
						   // 查询城市的一条记录
							if(!chengshi.equals("")){
								List<Area> csList = areaService.findAreaByName(chengshi, sf_id);
								for (int j = 0; j < csList.size(); j++){
									Area cs_area = csList.get(j);
									cs_id = cs_area.getId(); // 得到城市ID<*>
									
									Area area = new Area();
									area.setId(0);
									area.setName("请选择...");
									
									// 通过城市ID查询所有的区域，页面获取值<*>
									areaList = areaService.findAreaByParendIdAndlvType(cs_id, Area.AreaType.AREA);
									areaList.add(0, area);
									// 查询区域的一条记录
									if(!quyu.equals("")){
										List<Area> qyList = areaService.findAreaByName(quyu, cs_id); 
										for (int k = 0; k < qyList.size(); k++) {
											Area qy_area = qyList.get(j);
											qy_id = qy_area.getId(); // 得到区域ID<*>
										}
									}
								}
							}else{
								Area area = new Area();
								area.setId(0);
								area.setName("请选择...");
								cityList.add(0, area);
								areaList = new ArrayList<Area>();
								areaList.add(area);
							}
							 
	
					}
				}
			}
			setRequestAtrribute("companyList", comList);
			
			
			return "addUserSucc"; //处理-跳转到 [backStageManage/userInfoAdd.jsp]后台添加用户页面
		}
	}


	public void initMethodArea() {
		String shengfen = "";
		String chengshi = "";
		String  quyu = "";
		// 获取省列表,在前台显示省份
		provinces = areaService.findAreaByParendIdAndlvType(Area.NO_PARENT,
				Area.AreaType.PROVINCE);
		if(null != user){
			if(null != user.getProvince() && !user.getProvince().equals("")){
				String provinceid =	user.getProvince(); //省份ID
				//通过省份ID查询获取名称
				 Area areaProvince = areaService.findById(Integer.valueOf(provinceid));
				 shengfen = areaProvince.getName(); //获取省份
			 }
			 
			 if(null != user.getCity() && !user.getCity().equals("")){
				 String cityid =user.getCity();  //城市ID
				 Area areaCity = areaService.findById(Integer.valueOf(cityid));
				 chengshi = areaCity.getName(); //获取城市
			 }
			 if(null != user.getZone() && !user.getZone().equals("")){
				 String zoneid= user.getZone();   //区县ID
				 Area areaZone = areaService.findById(Integer.valueOf(zoneid));
				 quyu = areaZone.getName();  //获取区县
			 }

			 if(shengfen.equals("")){
				 Area area = new Area();
					area.setId(0);
					area.setName("请选择...");
				 cityList = new ArrayList<Area>();
				 cityList.add(area);
				 areaList = new ArrayList<Area>();
				 areaList.add(area);
			 }else {
				// 查询省份的一条记录
				List<Area> sfList = areaService.findAreaByNameTypeid(shengfen,Area.AreaType.PROVINCE); 
				for (int i = 0; i < sfList.size(); i++) {
					Area sf_area = sfList.get(i);
					sf_id = sf_area.getId(); // 得到省份ID<*>
					// 通过省份ID查询所有城市，页面获取值<*>
					cityList = areaService.findAreaByParendIdAndlvType(sf_id,Area.AreaType.CITY);
					   // 查询城市的一条记录
						if(!chengshi.equals("")){
							List<Area> csList = areaService.findAreaByName(chengshi, sf_id);
							for (int j = 0; j < csList.size(); j++){
								Area cs_area = csList.get(j);
								cs_id = cs_area.getId(); // 得到城市ID<*>
								
//								Area area = new Area();
//								area.setId(0);
//								area.setName("请选择...");
								
								// 通过城市ID查询所有的区域，页面获取值<*>
								areaList = areaService.findAreaByParendIdAndlvType(cs_id, Area.AreaType.AREA);
								//areaList.add(0, area);
								// 查询区域的一条记录
								if(!quyu.equals("")){
									List<Area> qyList = areaService.findAreaByName(quyu, cs_id); 
									for (int k = 0; k < qyList.size(); k++) {
										Area qy_area = qyList.get(j);
										qy_id = qy_area.getId(); // 得到区域ID<*>
									}
								}
							}
						}else{
							Area area = new Area();
//							area.setId(0);
//							area.setName("请选择...");
//							cityList.add(0, area);
							areaList = new ArrayList<Area>();
							//areaList.add(area);
						}
						 

				}
			}
//			 HttpServletRequest request = ServletActionContext.getRequest();
//			 request.setAttribute("user", user);
			// setRequestAtrribute("user", user);
		}	
	
	}
	
	public String filterType(String[] types) {
		// String fileType = getPicContentType();
		// for (String type : types) {
		// if (type.startsWith("image")) {
		// return null;
		// }
		// }
		if (this.getPicContentType().startsWith("image")) {
			return null;
		}
		return INPUT;
	}

	public long getMaximumSize() {
		return maximumSize;
	}

	public void setMaximumSize(long maximumSize) {
		this.maximumSize = maximumSize;
	}

	public String getAllowTypes() {
		return allowTypes;
	}

	public void setAllowTypes(String allowTypes) {
		this.allowTypes = allowTypes;
	}

	public File getPic() {
		return pic;
	}

	public void setPic(File pic) {
		this.pic = pic;
	}

	public String getPicContentType() {
		return picContentType;
	}

	public void setPicContentType(String picContentType) {
		this.picContentType = picContentType;
	}

	public String getPicFileName() {
		return picFileName;
	}

	public void setPicFileName(String picFileName) {
		this.picFileName = picFileName;
	}
	public UserInfoService getUserInfoService() {
		return userService;
	}
	public void setUserInfoService(UserInfoService userService) {
		this.userService = userService;
	}

	public UserInfo getUser() {
		return user;
	}

	public void setUser(UserInfo user) {
		this.user = user;
	}

	public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public AreaService getAreaService() {
		return areaService;
	}

	public void setAreaService(AreaService areaService) {
		this.areaService = areaService;
	}

	public List<Area> getProvinces() {
		return provinces;
	}

	public void setProvinces(List<Area> provinces) {
		this.provinces = provinces;
	}

	public List<Area> getCityList() {
		return cityList;
	}

	public void setCityList(List<Area> cityList) {
		this.cityList = cityList;
	}

	public List<Area> getAreaList() {
		return areaList;
	}

	public void setAreaList(List<Area> areaList) {
		this.areaList = areaList;
	}

	public Integer getSf_id() {
		return sf_id;
	}

	public void setSf_id(Integer sfId) {
		sf_id = sfId;
	}

	public Integer getCs_id() {
		return cs_id;
	}

	public void setCs_id(Integer csId) {
		cs_id = csId;
	}

	public Integer getQy_id() {
		return qy_id;
	}

	public void setQy_id(Integer qyId) {
		qy_id = qyId;
	}
	
	
	
}
